package com.example.archivemanagement.service.impl;


import cn.hutool.json.JSONUtil;
import com.example.archivemanagement.service.HdfsService;
import com.example.archivemanagement.utils.SparkUtils;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class HdfsServiceImpl implements HdfsService {

    @Value("${file.upload-dir}")
    private String uploadDir;


    @Override
    public Map<String, String> uploadFile(MultipartFile file, String hdfsPath) {
        Path filePath;
        String fileName = StringUtils.cleanPath(file.getOriginalFilename());
        try {
            Path uploadPath = Paths.get(uploadDir);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }
            filePath = uploadPath.resolve(fileName);
            Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        /*Map<String, String> map = Maps.newHashMap();
        map.put("operator", "upload");
        map.put("status", "success");
        map.put("path", hdfsPath);
        map.put("size", "111111");
        map.put("destPath", "hdfs://192.168.1.100:9000" + hdfsPath + "/" + fileName);
        return map;*/
        return SparkUtils.createSparkSession("upload", filePath.toAbsolutePath().toString(), "hdfs://192.168.91.128:9000" + hdfsPath);
    }

    @Override
    public Map<String, String> viewFile(String fileName) {
        return SparkUtils.createSparkSession("read", "hdfs://192.168.91.128:9000" + fileName, null);
    }

    @Override
    public String download(String fileName) {
        return SparkUtils.getHdfsFileContent(fileName);
    }
}
